<?php

namespace plugin\admin\app\controller;

use plugin\admin\app\model\Admin;
use plugin\admin\app\model\AdminRole;
use support\Request;
use support\Response;
use plugin\admin\app\model\AdminLog;
use plugin\admin\app\controller\Crud;
use support\exception\BusinessException;

/**
 * 操作日志
 */
class AdminLogController extends Crud
{

    /**
     * @var AdminLog
     */
    protected $model = null;

    /**
     * 构造函数
     *
     * @return void
     */
    public function __construct()
    {
        $this->model = new AdminLog;
    }

    /**
     * 浏览
     *
     * @return Response
     */
    public function index(): Response
    {
        return view('admin-log/index');
    }

    /**
     * 查询
     *
     * @param Request $request
     * @return Response
     * @throws BusinessException
     */
    public function select(Request $request): Response
    {
        [$where, $format, $limit, $field, $order] = $this->selectInput($request);
        $query = $this->doSelect($where, $field, $order);
        if ($format === 'select') {
            return $this->formatSelect($query->get());
        }
        $paginator  = $query->paginate($limit);
        $items      = $paginator->items();
        $admin_ids  = array_column($items, 'admin_id');
        $admins     = Admin::whereIn('id', $admin_ids)->get();
        $admins_map = [];
        foreach ($admins as $vlue) {
            $admins_map[$vlue['id']][] = $vlue['username'];
        }

        foreach ($items as $index => $item) {
            $items[$index]['admin_name'] = isset($admins_map[$item['admin_id']]) ? implode(',', $admins_map[$item['admin_id']]) : '';
        }

        $res = json(['code' => 0, 'msg' => 'ok', 'count' => $paginator->total(), 'data' => $items]);
        return $res;
    }

    /**
     * 插入
     *
     * @param Request $request
     * @return Response
     * @throws BusinessException
     */
    public function insert(Request $request): Response
    {
        if ($request->method() === 'POST') {
            return parent::insert($request);
        }
        return view('admin-log/insert');
    }

    /**
     * 更新
     *
     * @param Request $request
     * @return Response
     * @throws BusinessException
     */
    public function update(Request $request): Response
    {
        if ($request->method() === 'POST') {
            return parent::update($request);
        }
        return view('admin-log/update');
    }

}
